<template>
  <div>
    <van-nav-bar left-arrow left-text="返回" @click-left="$router.back()">
      <h3 slot="title">登录</h3>
    </van-nav-bar>
    <van-row>
      <van-form @submit="login">
        <van-cell-group>
          <van-field label="用户名" name="username" v-model="loginInfo.username" placeholder="请输入用户名" :rules="[{required:true,message:'用户名不能为空'}]"/>
          <van-field label="密码" name="password" type="password" :rules="[{required:true,message: '密码不能位空'}]" v-model="loginInfo.password" placeholder="请输入密码" />
          <van-field label="验证码" name="captchCode" :rules="[{validator:checkCaptch,message:'验证码长度为4'}]" v-model="loginInfo.captchaCode" placeholder="请输入验证码">
            <template slot="extra">
              <van-image :src="captchSrc" @click="getCaptch" width="60" height="20"></van-image>
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 5px 10px">
          <van-button native-type="submit" type="info" block round>提交</van-button>
        </div>
      </van-form>
    </van-row>
  </div>
</template>

<script>
const loginInfo = {
  username: '',
  password: '',
  captchaCode: '',
  captchCodeId: ''
}
export default {
  name: 'Login',
  data () {
    return {
      loginInfo: { ...loginInfo },
      captchSrc: ''
    }
  },
  methods: {
    getCaptch () {
      this.$axios.post('/v1/captchas').then(({ data }) => {
        if (data.code === 20000) {
          this.loginInfo.captchCodeId = data.data.captchCodeId
          this.captchSrc = data.data.code
        }
      })
    },
    checkCaptch (val) {
      return val.length === 4
    },
    login () {
      this.$axios.post('/v1/users/v2/login', this.loginInfo).then(({ data }) => {
        if (data.user_id) {
          this.$cookies.set('user_id', data.user_id)
          this.$store.dispatch('getUserInfo')
          this.$notify({
            message: '登录成功',
            type: 'success',
            onClose: () => {
              this.loginInfo = { ...loginInfo }
              this.$router.replace('/about')
            }
          })
        } else {
          this.$dialog.alert({ message: data.message }).then(() => {
            this.loginInfo = { ...loginInfo }
            this.getCaptch()
          })
        }
      })
    }
  },
  created () {
    this.$nextTick(() => {
      this.getCaptch()
    })
  }
}
</script>

<style scoped>

</style>
